<template>
    <div>
        <SuperTable ref="table" path="/partner/index" :params="params" :columns="columns">
            <Button slot="header-left" icon="ios-download-outline" type="primary" @click="handleExport">导出筛选数据</Button>
            <div slot="header-right">
                <Form ref="filter" :model="filter" inline>
                    <FormItem label="关键词">
                        <Input v-model="filter.keywords" clearable placeholder="商户号、名称、手机号" style="width: 200px;" />
                    </FormItem>
                    <FormItem label="类型" prop="type">
                        <Select v-model="filter.type" clearable style="width: 80px">
                            <Option :value="1">企业</Option>
                            <Option :value="2">个人</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="状态" prop="status">
                        <Select v-model="filter.status" clearable style="width: 80px">
                            <Option :value="0">未认证</Option>
                            <Option :value="1">已认证</Option>
                        </Select>
                    </FormItem>
                    <Button type="primary" @click="handlFilter">筛选</Button>
                </Form>
            </div>
        </SuperTable>

        <Modal title="保证金流水" v-model="showModalDeposit" :width="960" @on-cancel="showModalDeposit = false">
            <SuperTable v-if="showModalDeposit" :fixedFooter="false" size="small" path="/partner/deposit/index" :params="paramsDeposit" :columns="columnsDeposit"></SuperTable>
            <div slot="footer">
                <Button @click="showModalDeposit = false">关闭</Button>
            </div>
        </Modal>

        <Modal title="保证金充值流水" v-model="showModalDepositRecharge" :width="960" @on-cancel="showModalDepositRecharge = false">
            <SuperTable v-if="showModalDepositRecharge" :fixedFooter="false" size="small" path="/partner/depositRecharge/index" :params="paramsDepositRecharge" :columns="columnsDepositRecharge"></SuperTable>
            <div slot="footer">
                <Button @click="showModalDepositRecharge = false">关闭</Button>
            </div>
        </Modal>

        <Modal title="余额流水" v-model="showModalBalance" :width="960" @on-cancel="showModalBalance = false">
            <SuperTable v-if="showModalBalance" :fixedFooter="false" size="small" path="/partner/balance/index" :params="paramsBalance" :columns="columnsBalance"></SuperTable>
            <div slot="footer">
                <Button @click="showModalBalance = false">关闭</Button>
            </div>
        </Modal>

        <Modal title="冻结流水" v-model="showModalFreeze" :width="960" @on-cancel="showModalFreeze = false">
            <SuperTable ref="tableFreeze" v-if="showModalFreeze" :fixedFooter="false" size="small" path="/partner/freeze/index" :params="paramsFreeze" :columns="columnsFreeze"></SuperTable>
            <div slot="footer">
                <Button @click="showModalFreeze = false">关闭</Button>
            </div>
        </Modal>

        <Modal title="充值保证金" v-model="showRechargeModal" :width="380" @on-cancel="handleCancelRecharge">
            <Form ref="form" :model="form" :rules="rules" :label-width="80">
                <FormItem label="服务商" prop="name">
                    <Input v-model="form.name" disabled />
                </FormItem>
                <FormItem label="当前保证金" prop="money">
                    <Input v-model="form.money" disabled />
                </FormItem>
                <FormItem label="充值金额" prop="amount">
                    <InputNumber v-model="form.amount" :min="0.01" :precision="2" :active-change="false" style="width: 50%;"></InputNumber>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button :disabled="submiting" @click="handleCancelRecharge">取消</Button>
                <Button type="primary" :loading="submiting" @click="handleSubmitRecharge">提交</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import SuperTable from '@/components/utils/super-table.vue';
import TableRows from '@/components/utils/table-rows.vue';
import axios from "axios";
import { host } from '@/config/index.js';
import Cookies from 'js-cookie';
import { copy } from '@/libs/tools';
export default {
    components: {
        SuperTable,
        TableRows
    },
    data() {
        return {
            //充值弹窗
            showRechargeModal: false,
            submiting: false,
            form: {
                name: '',
                money: 0.0,
                partner_id: '',
                amount: 0,
            },
            rules: {
                amount: [
                    {required: true, type: 'number', message: '请输入充值金额', trigger: 'blur'}
                ]
            },
            showModalDeposit: false,
            showModalDepositRecharge: false,
            showModalBalance: false,
            showModalFreeze: false,
            //保证金流水
            paramsDeposit: {
                page: 1,
                pageSize: 10,
            },
            columnsDeposit: [
                {
                    title: '类型',
                    key: 'desc'
                },
                {
                    title: '变动前',
                    key: 'before_amount'
                },
                {
                    title: '金额',
                    render: (h, params) => {
                        return h("span", params.row.amount > 0 ? '+'+params.row.amount : params.row.amount) 
                    }
                },
                {
                    title: '变动后',
                    key: 'after_amount'
                },
                {
                    title: '时间',
                    key: 'created_at'
                },
            ],
            //保证金充值流水
            paramsDepositRecharge: {
                page: 1,
                pageSize: 10,
            },
            columnsDepositRecharge: [
                {
                    title: '渠道',
                    key: 'channel_text'
                },
                {
                    title: '金额',
                    key: 'amount'
                },
                {
                    title: '状态',
                    key: 'status_text'
                },
                {
                    title: '支付单号',
                    key: 'pay_sn'
                },
                {
                    title: '时间',
                    key: 'created_at'
                },
            ],
            //余额流水
            paramsBalance: {
                page: 1,
                pageSize: 10,
            },
            columnsBalance: [
                {
                    title: '类型',
                    key: 'type_text'
                },
                {
                    title: '变动前',
                    key: 'before_amount'
                },
                {
                    title: '金额',
                    render: (h, params) => {
                        return h("span", params.row.amount > 0 ? '+'+params.row.amount : params.row.amount) 
                    }
                },
                {
                    title: '变动后',
                    key: 'after_amount'
                },
                {
                    title: '订单',
                    key: 'partner_osn'
                },
                {
                    title: '时间',
                    key: 'created_at'
                }
            ],
            //冻结流水
            paramsFreeze: {
                page: 1,
                pageSize: 10,
            },
            columnsFreeze: [
                {
                    title: '类型',
                    key: 'desc'
                },
                {
                    title: '金额',
                    key: 'amount'
                },
                {
                    title: '订单',
                    key: 'partner_osn'
                },
                {
                    title: '状态',
                    key: 'status_text'
                },
                {
                    title: '时间',
                    key: 'created_at'
                },
                {
                    title: '操作',
                    align: "center",
                    key: "action",
                    width: 200,
                    render: (h, params) => {
                        let btns = [
                            h("Poptip",{
                                props:{
                                    transfer: true,
                                    confirm: true,
                                    title: '您确定要解冻这笔资金吗？'
                                },
                                on: {
                                    'on-ok': () => {
                                        this.$ajax.post('/order/partner/unfreeze', {partner_osn: params.row.partner_osn}).then(() => {
                                            this.$Message.success('操作成功');
                                            this.$refs.tableFreeze.reload();
                                            this.$refs.table.reload();
                                        }).catch(err => {
                                            this.$Message.error(err.message || '操作失败');
                                        })
                                    }
                                }
                            },[
                                h("Button", {
                                    props: {
                                        type: "primary",
                                        size: "small",
                                        disabled: params.row.status != 0
                                    }
                                }, "解冻")
                            ])
                        ];
                        return h("div", btns);
                    }
                }
            ],
            filter: {
                keywords: '',
                type: '',
                status: '',
            },
            params: {
                keywords: '',
                type: '',
                status: '',
                page: 1,
                pageSize: 10,
            },
            columns: [
                {
                    title: '基本信息',
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',`商户号：${params.row.id}`),
                            h('p',`手机号：${params.row.phone}`)
                        ])
                    }
                },
                {
                    title: '名称&类型',
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',params.row.name),
                            h('p',params.row.type_text),
                        ])
                    }
                },
                {
                    title: '保证金&总余额',
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',[
                                h('div',[
                                    h('span',`保证金：${params.row.account ? params.row.account.deposit : 0}`),
                                    h('a',{
                                        style:{
                                            color: '#fd9827',
                                            marginLeft: '10px'
                                        },
                                        on: {
                                            click: () => {
                                                this.paramsDeposit.partner_id = params.row.id;
                                                this.showModalDeposit = true;
                                            }
                                        }
                                    }, '流水'),
                                    h('a',{
                                        style:{
                                            color: '#fd9827',
                                            marginLeft: '10px'
                                        },
                                        on: {
                                            click: () => {
                                                this.paramsDepositRecharge.partner_id = params.row.id;
                                                this.showModalDepositRecharge = true;
                                            }
                                        }
                                    }, '充值流水')
                                ]),
                            ]),
                            h('p',`总余额：${params.row.account ? params.row.account.total : 0}`),
                        ])
                    }
                },
                {
                    title: '冻结资金&可用资金',
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',[
                                h('div',[
                                    h('span',`冻结资金：${params.row.account ? params.row.account.freeze : 0}`),
                                    h('a',{
                                        style:{
                                            color: '#fd9827',
                                            marginLeft: '10px'
                                        },
                                        on: {
                                            click: () => {
                                                this.paramsFreeze.partner_id = params.row.id;
                                                this.showModalFreeze = true;
                                            }
                                        }
                                    }, '流水')
                                ]),
                            ]),
                            h('p',[
                                h('div',[
                                    h('span',`可用资金：${params.row.account ? params.row.account.balance : 0}`),
                                    h('a',{
                                        style:{
                                            color: '#fd9827',
                                            marginLeft: '10px'
                                        },
                                        on: {
                                            click: () => {
                                                this.paramsBalance.partner_id = params.row.id;
                                                this.showModalBalance = true;
                                            }
                                        }
                                    }, '流水')
                                ]),
                            ]),
                        ])
                    }
                },
                {
                    title: '状态&注册时间',
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',params.row.status_text),
                            h('p',params.row.created_at),
                        ])
                    }
                },
                {
                    title: '账户信息',
                    render: (h, params) => {
                        let text = '开户人：' + (params.row.type == 1 ? params.row.name : params.row.real_name) + '\n' +
                                   '开户行：' + params.row.bank_name  + '\n' +
                                   '银行卡号：' + params.row.bank_account
                        return h('div', [
                            h("Poptip", {
                                props:{
                                    transfer: true,
                                    placement: 'left',
                                    trigger: 'hover',
                                    content: text,
                                    wordWrap: true
                                }
                            }, [
                                h("a",{
                                    on: {
                                        click: () => {
                                            copy(text,() => {
                                                this.$Message.success('复制成功');
                                            },() => {
                                                this.$Message.error('复制失败');
                                            });
                                        }
                                    }
                                },'复制账户')
                            ])
                        ]);
                    }
                },
                {
                    title: "操作",
                    align: "center",
                    key: "action",
                    width: 200,
                    render: (h, params) => {
                        let btns = [
                            h("Button", {
                                props: {
                                    type: "primary",
                                    size: "small"
                                },
                                on: {
                                    click: () => {
                                        this.form.name = params.row.name;
                                        this.form.money = params.row.account ? Number(params.row.account.deposit) : 0;
                                        this.form.partner_id = params.row.id;
                                        this.showRechargeModal = true;
                                    }
                                }
                            }, "充值保证金"),
                            h("Button", {
                                style: {
                                    marginLeft: "5px"
                                },
                                props: {
                                    type: "error",
                                    size: "small"
                                },
                                on: {
                                    click: () => {
                                        this.handleDelete(params.row);
                                    }
                                }
                            }, "删除")
                        ];
                        return h("div", btns);
                    }
                }
            ]
        }
    },
    methods: {
        handlFilter() {
            const { filter } = this;
            this.params.keywords = filter.keywords;
            this.params.type = filter.type;
            this.params.status = filter.status;
            this.$refs.table.init();
        },
        handleSubmitRecharge() {
            if(this.submiting) return false;
            this.$refs.form.validate((valid) => {
                if(valid) {
                    this.submiting = true;
                    let params = {
                        partner_id: this.form.partner_id,
                        amount: this.form.amount
                    }
                    this.$ajax.post('/partner/depositRecharge/recharge', params).then(res => {
                        this.$Message.success('充值成功');
                        this.submiting = false;
                        this.handleCancelRecharge();
                        this.$refs.table.init();
                    }).catch(err => {
                        this.submiting = false;
                        this.$Message.error(err.message || '充值失败');
                    })
                }
            })
        },
        handleCancelRecharge(){
            this.showRechargeModal = false;
            setTimeout(() => {
                this.form.name = '';
                this.form.money = 0.0;
                this.form.partner_id = '';
                this.form.amount = 0.0;
            }, 300)
        },
        handleDelete(row) {
            this.$Modal.confirm({
                title: "操作提示:",
                width: 320,
                content: `<p>您确定要删除商家‘${row.name}’吗?</p>`,
                onOk: () => {
                    const msg = this.$Message.loading({
                        content: '正在提交删除',
                        duration: 0
                    });
                    this.$ajax.delete('/project/delete', {params: {id:row.id}}).then(() => {
                        msg();
                        this.$Message.success('操作成功');
                        this.$refs.table.reload();
                    }).catch(err => {
                        msg();
                        this.$Message.error(err.message || '操作失败');
                    })
                }
            });
        },
        handleExport() {
            axios({
                url: host+'/partner/export', // 替换为你的文件URL
                headers: {Authorization: 'Bearer ' + Cookies.get('token')},
                data: this.filter,
                method: 'POST',
                responseType: 'blob', // 设置响应类型为blob
            }) .then((res) => {
                let blob = new Blob([res.data],{type:"application/octet-stream;"});
                let aLink = document.createElement("a");
                aLink.download = '服务商导出记录.xlsx';
                aLink.href = URL.createObjectURL(blob);
                aLink.dispatchEvent(
                    new MouseEvent("click", {
                        bubbles: true,
                        cancelable: true,
                        view: window,
                    })
                ); // 兼容火狐
            })
        },
    }
}
</script>